import { service } from "@/utils";
import { download } from "@/utils";
// 文件上传封装
export async function uploadFile(url, file, fieldName = "file", config = {}) {
  const formData = new FormData();
  formData.append(fieldName, file);
  return await service.post(url, formData, {
    ...config,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

// 文件下载封装
export async function downloadFile(url, params, method = "get", filename = "") {
  const res = await service[method](url, {
    data: params,
    responseType: "blob",
  });
  if (
    res.headers["content-type"].includes("application/json") &&
    !res.headers["content-disposition"]
  ) {
    // 可能有错
    const fileReader = new FileReader();
    fileReader.readAsText(result.data, "utf-8");
    fileReader.onload = (e) => {
      const data = JSON.parse(e.target.result);
    };
  } else {
    const downloadFileName =
      filename ||
      decodeURI(
        res.headers["content-disposition"].split("filename=")[1],
        "UTF-8"
      );
    const blob = new Blob([res.data]);
    return download(blob, downloadFileName);
  }
}
